<?php
/*
 * Copyright (c) 2021.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\base;


use app\common\model\system\Config;
use app\common\services\token\driver\Cache;
use think\Exception;

class BaseCloud extends BaseDriver
{
    protected $url = "http://golang.dkyx.cc";

    protected $port = "80";

    // 公共参数

    protected function getParams()
    {
        $cloud = Config::get("cloud");
        try {
            $params = array(
                'site_id' => $cloud['site_id'],
                'token'   => $cloud['token'],
                'domain'  => $cloud['domain'] ?: request()->server("SERVER_NAME")
            );
            return $params;
        } catch (Exception $e) {
            abort(-1, '云平台信息错误，请联系多客售后解决');
        }
    }


    public function go_request($path, $data)
    {
        return httpPost($this->url . ":" . $this->port . "/" . $path, $data);
    }

    public function api($data, $json = false)
    {
        $data['param'] = json_encode(array_merge($data['param'] ?? [], $this->getParams()));
        $res = $this->go_request("api", $data);

        if (!$json) {
            $res = json_decode($res, true);
        }
        if ($res['code'] === -110) {
            $this->setCloudStatus(false);
            abort(-1, '与云端服务器通讯失败');
        }

        return $res;
    }

    public function fun($data)
    {
        return $this->go_request("fun", $data);
    }

    public function setCloudStatus($status = null)
    {
        \think\facade\Cache::set('cloud-status', $status);
        return $status;
    }

    public function getCloudStatus()
    {
        $res = \think\facade\Cache::get('cloud-status');
        if ($res === false) {
            return false;
        } else {
            return true;
        }
    }

    public function addon($data)
    {
        return $this->go_request("app", $data);
    }

    protected function initialize(array $config)
    {
    }
}
